//
//  AILoginVc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/2/28.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "AILoginVc.h"
#import "DHGuidePageHUD.h"


#import "Reset_login_pwd_vc.h"
#import "Reg_step_one_vc.h"
#import "JKCountDownButton.h"
#import <FCUUID/FCUUID.h>
#import "AuthSignin_model.h"
#import "AppDelegate.h"

@interface AILoginVc ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet JKCountDownButton *get_checkCode_btn;
@property (weak, nonatomic) IBOutlet UITextField *phoneTf;
@property (weak, nonatomic) IBOutlet UITextField *codeTf;
@property (weak, nonatomic) IBOutlet UIButton *lookCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *yanzhengma_btn;
@property (weak, nonatomic) IBOutlet UILabel *code_tip_lb;

@end

@implementation AILoginVc
- (IBAction)req_send_checkCode_action:(JKCountDownButton *)sender {
    if ([Anktool strIsBlank:self.phoneTf.text]) {
        [MBProgressHUD showTipMessageInView:@"请输入手机号"];
        return;
    }else if(self.phoneTf.text.length != 11){
        [MBProgressHUD showTipMessageInView:@"请输入正确的手机号!"];
        return;
    }
    
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[Anktool strBlankHolder:self.phoneTf.text] forKey:@"mobile"];
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:channel_type forKey:@"channel_type"];
    
    
    [PPHTTPRequest req:@"api/Auth/sms" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            [MBProgressHUD showTipMessageInView:@"发送成功"];
            [self.codeTf becomeFirstResponder];
            sender.enabled = NO;
            //button type要 设置成custom 否则会闪动
            [sender startCountDownWithSecond:60];
            
            [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
                NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
                return title;
            }];
            [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
                countDownButton.enabled = YES;
                return @"点击重新获取";
                
            }];
            
            
        }
        
        else
//            if ([error_code isEqualToString:@""])
            {
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
    }];
}
- (IBAction)code_switch_action:(UIButton *)sender {
    
    if ([sender.currentTitle isEqualToString:@"验证码登录"]) {
        
        [sender setTitle:@"密码登录" forState:UIControlStateNormal];
        
        
        self.codeTf.placeholder = @"请输入验证码";
        self.codeTf.secureTextEntry = NO;
        self.codeTf.text = @"";
        
        if ([self.codeTf isFirstResponder]) {
            [self.codeTf resignFirstResponder];
            [self.codeTf setKeyboardType:UIKeyboardTypeNumberPad];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.codeTf becomeFirstResponder];
            });
        }else{
            [self.codeTf setKeyboardType:UIKeyboardTypeNumberPad];

        }
       
        self.code_tip_lb.text = @"验证码";
        
    }else{
        // 设置验证码登录
        [sender setTitle:@"验证码登录" forState:UIControlStateNormal];
        
        self.codeTf.secureTextEntry = YES;

        self.codeTf.placeholder = @"请输入6-16位字母数字";
        self.codeTf.text = @"";
        if ([self.codeTf isFirstResponder]) {
            [self.codeTf resignFirstResponder];
            [self.codeTf setKeyboardType:UIKeyboardTypeDefault];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.codeTf becomeFirstResponder];
            });
        }else{
            [self.codeTf setKeyboardType:UIKeyboardTypeDefault];

        }
        
        self.code_tip_lb.text = @"密码";
        
    }
    
    self.lookCodeBtn.hidden = !self.lookCodeBtn.hidden;
    self.get_checkCode_btn.hidden = !self.get_checkCode_btn.hidden;
    
}
- (IBAction)forgot_code_action:(UIButton *)sender {
    Reset_login_pwd_vc *vc= [[Reset_login_pwd_vc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.view endEditing:YES];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)loginAction:(UIButton *)sender {
    
    if(self.phoneTf.text.length != 11){
        [MBProgressHUD showTipMessageInView:@"请输入11位手机号"];
        return;
    }
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[Anktool strBlankHolder:self.phoneTf.text] forKey:@"mobile"];
    [dict setObject:app_code forKey:@"app_code"];
    
    
    
    NSString *url = @"";
    if ([self.code_tip_lb.text isEqualToString:@"密码"]) {
        
        if (self.codeTf.text.length < 6) {
            [MBProgressHUD showTipMessageInView:@"请输入6-16位字母数字组合"];
            return;
        }
//        [dict setObject:[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"] forKey:@"app_version"];
//        [dict setObject:[FCUUID uuidForDevice] forKey:@"imei"];
//        [dict setObject:@"1" forKey:@"account_type"];
        
        
        [dict setObject:self.codeTf.text forKey:@"password"];
        url = @"api/Auth/signin";
        // password=123456&mobile=18162152664&app_code=ainankang
        
        
        /*
         {
         "error_code":0,
         "error_msg":"操作成功",
         "data":{
         "user_info":{
         "id":84,
         "user_name":"18162152664",
         "avatar_url":"",
         "gender":0,
         "mobile":"18162152664",
         "status":1
         },
         "session_id":"642ce155-5cfe-11ea-acc6-00163e0b4265",
         "token":"wq56wqbCrcKxwqp6w519wqV0w5t9fMKXZsKBwrJ5acKCwojCksOcwrLCucKIwq_Ch8ONwpLCkcKqwrDCvmbCscOTwofDkn3CtcKIwpV8wozChsKgwpLCpcKJwqnCgsKIf8OPwr7CuGTCnsKSwpXChsKTwq3CisKmwq3CscK6wpLDoMKKwrV1w41-fHlowobCiXFy"
         }
         }
         */
    }else{
        
        if (self.codeTf.text.length != 6) {
            [MBProgressHUD showTipMessageInView:@"请输入6位数验证码"];
            return;
        }
        [dict setObject:self.codeTf.text forKey:@"verification"];
        [dict setObject:channel_type forKey:@"channel_type"];
        url = @"api/Auth/sign";
    }
    sender.userInteractionEnabled = NO;
    [PPHTTPRequest req:url parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            [self.codeTf resignFirstResponder];
            AuthSignin_model *signin = [AuthSignin_model mj_objectWithKeyValues:response];
            AppDelegate *delegate = [UIApplication sharedApplication].delegate;
            [delegate ank_switch_to_tab];
            if ([Anktool strIsBlank:signin.data.token]) {
                DLog(@"!!!!!!!!-----登录后token为空-----!!!!!!")
            }else{

                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:app_code forKey:@"appCode"];
                [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
                
                
                
                
                
                [PPHTTPRequest req:@"java/app/user/getUserInfo" parameters:dict success:^(id response) {
                    NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
                    if ([error_code isEqualToString:@"0"]) {
                        /*
                         {
                         "error_msg": "操作成功",
                         "data": {
                         "userId": 113,
                         "nickName": "15979836292",
                         "avatarUrl": "",
                         "mobile": null
                         },
                         "error_code": 0
                         }
                         */
                        NSDictionary *data_dic = response[@"data"];
                        NSString *nickName = [NSString stringWithFormat:@"%@", data_dic[@"nickName"]];
                        NSString *avatarUrl = [NSString stringWithFormat:@"%@", data_dic[@"avatarUrl"]];
                        NSString *mobile = [NSString stringWithFormat:@"%@", data_dic[@"mobile"]];
                        AuthSignin_model.sharedInstance.data.user_info.avatar_url = avatarUrl;
                        AuthSignin_model.sharedInstance.data.user_info.nick_name = nickName;
                        AuthSignin_model.sharedInstance.data.user_info.mobile = mobile;
                        NSString *dictStr = [AuthSignin_model.sharedInstance mj_JSONString];
                        [[NSUserDefaults standardUserDefaults] setObject:dictStr forKey:@"ank_sign"];
                        
                        [[NSUserDefaults standardUserDefaults] setObject:signin.data.user_info.mobile forKey:@"login_or_not"];
                       
                        
                        
                    }
                    else{
                        
                        
                        DLog(@"%@", response[@"error_msg"]);
                        
                    }
                    
                } failure:^(NSError *error) {
                    DLog(@"%@", [error localizedDescription]);
                    
                }];
                
                
            }
        }
        else  {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
        sender.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
        sender.userInteractionEnabled = YES;
        
    }];
    
}
- (IBAction)lookCodeAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.codeTf.secureTextEntry = !self.codeTf.secureTextEntry ;
}
- (IBAction)regAction:(UIButton *)sender {
    Reg_step_one_vc *vc= [[Reg_step_one_vc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.view endEditing:YES];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置APP引导页
    if (![[NSUserDefaults standardUserDefaults] boolForKey:BOOLFORKEY]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:BOOLFORKEY];
        // 静态引导页
        [self setStaticGuidePage];
        
        // 动态引导页
        // [self setDynamicGuidePage];
        
        // 视频引导页
        // [self setVideoGuidePage];
    }
    
    self.get_checkCode_btn.layer.borderWidth = 1;
    self.get_checkCode_btn.layer.borderColor = themeColor.CGColor;
    
   self.codeTf.delegate = self.phoneTf.delegate = self;
}


#pragma mark - 设置APP静态图片引导页
- (void)setStaticGuidePage {
    NSArray *imageNameArray = @[@"guideImage1.jpg",@"guideImage2.jpg",@"guideImage3.jpg"];
    DHGuidePageHUD *guidePage = [[DHGuidePageHUD alloc] dh_initWithFrame:self.navigationController.view.bounds imageNameArray:imageNameArray buttonIsHidden:YES];
    guidePage.slideInto = YES;
    [self.navigationController.view addSubview:guidePage];
}

#pragma mark - ================== tf delegate ==================
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSMutableString *newtxt = [NSMutableString stringWithString:textField.text];
    
    
    [newtxt replaceCharactersInRange:range withString:string];
    
    // 客户端仅仅判断手机号是否11位
    if ([textField isEqual:self.phoneTf]) {// 手机号11位
        int MAX_CHARS = 11;
        
        return ([newtxt length] <= MAX_CHARS);
        
    }else if([textField isEqual:self.codeTf]){
        if ([self.code_tip_lb.text isEqualToString:@"密码"]) {
            
            
            return ([newtxt length] <= 16 && [Anktool is_num_alpha:newtxt]);

        }else{
            return ([newtxt length] <= 6);

        }
        
    }
    
    
    return YES;
    
}


@end
